#include <stdio.h>
#include <string.h>

#include "hw_jpeg_decode_api.h"

#define LocalPrint(_outfd_, _fmt_, ...) fprintf(_outfd_, "%s:%d\t\t" _fmt_, __FUNCTION__, __LINE__, ##__VA_ARGS__)

char* jpeg_image = NULL;

int open_jpeg_file(char* file_name){
	int flen = 0;
/* Reading input file */
    FILE *fIn = fopen(file_name, "rb");
    if(fIn == NULL)
    {
        fprintf(stdout, "Unable to open input file\n");
        exit(0);
    }

    /* file i/o pointer to full */
    fseek(fIn, 0L, SEEK_END);
    flen = ftell(fIn);
    rewind(fIn);

	jpeg_image = malloc(flen);
    /* read input stream from file to buffer and close input file */
    fread(jpeg_image, sizeof(uint8_t), flen, fIn);
    fclose(fIn);
	return flen;
}

extern void fb_clean();
extern void fb_blit(uint32_t* addr, int sw, int sh);
int main(int argc,char* argv[]){
	int len = open_jpeg_file(argv[1]);
	int i;
	void* decoder = hw_jpeg_decoder_init();
	int w,h;
	if(hw_jpeg_decoder_set_src(decoder, jpeg_image, len)){
		LocalPrint(stderr, "%s\n", "hw_jpeg_decoder_set_src failed.\n");
		return -1;
	}
	hw_jpeg_decoder_getsize(decoder, &w, &h);
	LocalPrint(stderr,"image info: %dx%d.\n", w, h);
	char* pixels_data = malloc(w*h*4);
	for(i=0;i<100;i++){
		if(hw_jpeg_decoder_on_frame(decoder, pixels_data)){
			LocalPrint(stderr, "%s\n", "hw_jpeg_decoder_on_frame failed.\n");
			return -1;
		}
		fb_clean();
		fb_blit(pixels_data, w, h);		
	}
	free(pixels_data);
	hw_jpeg_decoder_deinit(decoder);
	free(jpeg_image);
	return 0;
}


